﻿using System;
using System.Collections.Generic;

namespace HAOest.Data.SQLite
{
    /// <summary>
    /// 简单key-value型数据库
    /// </summary>
    public class SimpleDatabase
    {
        private SQLite sqlite = null;
        private string tableName = "simpleTable";   //表名

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="databaseFileName">数据库文件名</param>
        /// <param name="password">可选密码</param>
        public SimpleDatabase(string databaseFileName, string password = null)
        {
            sqlite = new SQLite(databaseFileName, password);
            sqlite.CreateTableIfNotExists(tableName, "key", false, "value");
        }

        /// <summary>
        /// 设置键值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void SetValue(string key, string value)
        {
            List<string> columnNames = new List<string> { "key", "value" };
            List<string> values = new List<string> { key, value };
            sqlite.Insert(tableName, columnNames, values);
        }

        /// <summary>
        /// 查找键值
        /// </summary>
        /// <param name="key"></param>
        private string GetValue(string key)
        {
            return sqlite.Select(tableName, "value", "key='" + key + "'");
        }

        /// <summary>
        /// 获取整数键值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int GetIntValue(string key)
        {
            string value = GetValue(key);
            try
            {
                return int.Parse(value);
            }
            catch (ArgumentNullException ex)
            {
                throw new ArgumentNullException("key", string.Format("键值为空，不是整数\n原始信息：{0}", ex.Message));
            }
            catch (FormatException ex)
            {
                throw new FormatException(string.Format("键值内容{0}不是整数，无法转换\n原始信息：{1}", value, ex.Message));
            }
        }

        /// <summary>
        /// 获取字符串键值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetStringValue(string key)
        {
            return GetValue(key);
        }
    }
}
